package cn.itsource.org.controller;

import cn.itsource.basic.anno.PreAuthorize;
import cn.itsource.basic.config.BussinessException;
import cn.itsource.basic.util.AjaxResult;
import cn.itsource.basic.util.LoginContext;
import cn.itsource.basic.util.PageList;
import cn.itsource.org.domain.Department;
import cn.itsource.org.query.DepartmentQuery;
import cn.itsource.org.service.IDepartmentService;
import cn.itsource.user.domain.Logininfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@RestController
@RequestMapping("/dept")
@Api(value = "部门的API", description = "部门相关的CRUD功能")
//@LogAnno
@PreAuthorize
public class DepartmentController {


    @Autowired
    private IDepartmentService departmentService;

    /**
     * 添加/修改
     */
    @PutMapping
    public AjaxResult addOrUpdate(@RequestBody Department department) {
        if (null == department.getId()) {
            // 添加
            departmentService.add(department);
        } else {
            // 修改
            departmentService.update(department);
        }
        return AjaxResult.me().success();
    }

    /**
     * 删除 delete localhost:8080/dept/1
     */
    @DeleteMapping("/{id}")
    @PreAuthorize(name = "根据id查询部门",sn = "department:delete")
    public AjaxResult delete(@PathVariable("id") Long id) {
        departmentService.delete(id);
        return AjaxResult.me().success();
    }

    /**
     * 查询所有
     */
    @GetMapping
    @ApiOperation(value = "查询所有部门数据")
    public List<Department> findAll() {
        return departmentService.findAll();
    }

    /**
     * 根据id查询一个
     */
    @GetMapping("/{id}")
    @ApiOperation(value = "通过ID查询")
    @PreAuthorize(name = "根据id查询部门",sn = "department:findById")
    public Department findById(@ApiParam(value = "ID属性", required = true) @PathVariable("id") Long id) {
        return departmentService.findById(id);
    }

    /**
     * 分页查询
     */
    @PostMapping
//    @LogAnno(method = "queryByPage",methodDes = "分页查询部门")
    @PreAuthorize(name = "分页查询部门",sn = "department:queryByPage")
    public PageList<Department> queryByPage(@RequestBody DepartmentQuery query, HttpServletRequest request) {
        Logininfo logininfo = LoginContext.getLogininfo(request);
        System.out.println(logininfo);
        return departmentService.queryByPage(query);
    }

    @PatchMapping
    @PreAuthorize(name = "批量删除部门",sn = "department:batchDel")
    public AjaxResult batchDel(@RequestBody List<Long> ids) {
        departmentService.batchDel(ids);
        return AjaxResult.me().success();
    }

    @PostMapping("/tree")
    @PreAuthorize(name = "查询部门树",sn = "department:tree")
    public List<Department> deptTree() {
        return departmentService.deptTree();
    }
}
